package org.shangrila.app.sys.shiro;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/** 
 * 根据用户账号和原始密码生成salt和password.
 * 用户账号和原始密码在登陆界面或维护界面输入，密码会MD5传输到服务端处理。服务端不知道初始明文密码。
 * 服务端处理：接受Md5后的密码初始值（encryptMD5(password)）：
 * encryptSalt(username,encryptMD5(password))  生成salt
 * encryptPassword(username,encryptMD5(password)) 生成密码
 */  
public class AppEncryptService {
	/**
	 * 登陆验证：password=md5(salt)
	 * @param username
	 * @param password（MD5）
	 * @return
	 */
    public static String encryptPassword(String username,String password) {               
        return encryptMD5(encryptSalt(username,password));
    }

    /**
     * 登陆验证:slat=md5(username+password（md5)
     * @param username
     * @param password（MD5）
     * @return
     */
    public static String encryptSalt(String username,String password) {  	           
        return encryptMD5(username+password);
    }

    /** 
     * 登陆验证
     * 功能简述: 使用md5进行单向加密. 
     */  
    public static String encryptMD5(String plainText) {  
    	MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance("md5");
	        byte[] cipherData = md5.digest(plainText.getBytes());  
	        StringBuilder builder = new StringBuilder();  
	        for(byte cipher : cipherData) {  
	            String toHexStr = Integer.toHexString(cipher & 0xff);  
	            builder.append(toHexStr.length() == 1 ? "0" + toHexStr : toHexStr);  
	        }  
	        return builder.toString();  
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		return null;         
    }  
    
    /** 
     * 新增用户/重置密码：将生成的salt/密码存入数据库
     * 功能简述: 根据用户账号和原始密码生成salt和password. 
     * @param username
     * @param password
     * @return
     */  
    public static String genEncryptSalt(String username,String password) {  
    	return encryptSalt(username,encryptMD5(password)); 
        }
    public static String genEncryptPassword(String username,String password) {  
    	return encryptPassword(username,encryptMD5(password)); 
        }

    /** 
     * 根据用户账号和原始密码生成salt和password.
     */  
    public static void testEncryptPassword(String username,String password) {  
    	System.out.println("username:" + username); 
    	System.out.println("password:" + password); //用户输入初始密码，MD5传输到服务端
		String md5Str = encryptMD5(password);
		String salt = genEncryptSalt(username,password);
		String pass = genEncryptPassword(username,password);
		System.out.println("md5(password):" + md5Str); //密码传输到服务端的初始密码
		System.out.println("slat:" + salt); 
		System.out.println("password:" + pass); 

        }

	public static void main(String[] args) {
		testEncryptPassword("root","000000");	
		testEncryptPassword("guest","guest");	
		testEncryptPassword("test","test");			
		testEncryptPassword("XieHongHua","shangrila");			
		testEncryptPassword("bme","123456");	
		
	}
}
